package com.crawler.system.controller;

import com.crawler.system.dto.CommonResult;
import com.crawler.system.dto.PageResult;
import com.crawler.system.entity.ProxyIp;
import com.crawler.system.service.ProxyIpService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 代理IP控制器
 * 提供代理IP的管理功能
 */
@Slf4j
@RestController
@RequestMapping("/proxy")
@RequiredArgsConstructor
@Tag(name = "代理IP服务接口", description = "代理IP的增删改查、验证和分配等接口")
public class ProxyIpController {

    private final ProxyIpService proxyIpService;

    @PostMapping
    @Operation(summary = "添加代理IP", description = "添加新的代理IP")
    @PreAuthorize("hasAuthority('crawler:proxy:create')")
    public CommonResult<Boolean> addProxy(@Valid @RequestBody ProxyIp proxyIp) {
        log.info("添加代理IP: {}", proxyIp);
        boolean result = proxyIpService.saveProxy(proxyIp);
        return CommonResult.success(result, "添加代理IP成功");
    }

    @PutMapping("/{id}")
    @Operation(summary = "更新代理IP", description = "更新指定ID的代理IP信息")
    @PreAuthorize("hasAuthority('crawler:proxy:update')")
    public CommonResult<Boolean> updateProxy(
            @Parameter(description = "代理IP ID", required = true) @PathVariable Long id,
            @Valid @RequestBody ProxyIp proxyIp) {
        log.info("更新代理IP: {}, {}", id, proxyIp);
        proxyIp.setId(id);
        boolean result = proxyIpService.updateProxy(proxyIp);
        return CommonResult.success(result, "更新代理IP成功");
    }

    @DeleteMapping("/{id}")
    @Operation(summary = "删除代理IP", description = "删除指定ID的代理IP")
    @PreAuthorize("hasAuthority('crawler:proxy:delete')")
    public CommonResult<Boolean> deleteProxy(
            @Parameter(description = "代理IP ID", required = true) @PathVariable Long id) {
        log.info("删除代理IP: {}", id);
        boolean result = proxyIpService.deleteProxy(id);
        return CommonResult.success(result, "删除代理IP成功");
    }

    @GetMapping("/{id}")
    @Operation(summary = "获取代理IP详情", description = "获取指定ID的代理IP详情")
    @PreAuthorize("hasAuthority('crawler:proxy:view')")
    public CommonResult<ProxyIp> getProxy(
            @Parameter(description = "代理IP ID", required = true) @PathVariable Long id) {
        log.info("获取代理IP详情: {}", id);
        ProxyIp proxyIp = proxyIpService.getProxyById(id);
        return CommonResult.success(proxyIp);
    }

    @GetMapping
    @Operation(summary = "获取代理IP列表", description = "分页获取代理IP列表，支持多种查询条件")
    @PreAuthorize("hasAuthority('crawler:proxy:list')")
    public CommonResult<PageResult<ProxyIp>> listProxies(
            @Parameter(description = "页码，从1开始") @RequestParam(defaultValue = "1") Integer pageNum,
            @Parameter(description = "每页条数") @RequestParam(defaultValue = "10") Integer pageSize,
            @Parameter(description = "IP地址，模糊匹配") @RequestParam(required = false) String ip,
            @Parameter(description = "端口") @RequestParam(required = false) Integer port,
            @Parameter(description = "类型：HTTP、HTTPS、SOCKS4、SOCKS5") @RequestParam(required = false) String type,
            @Parameter(description = "国家/地区") @RequestParam(required = false) String country,
            @Parameter(description = "状态：VALID-有效，INVALID-无效") @RequestParam(required = false) String status,
            @Parameter(description = "是否匿名") @RequestParam(required = false) Boolean anonymous) {
        
        log.info("获取代理IP列表，参数 pageNum={}, pageSize={}, ip={}, port={}, type={}, country={}, status={}, anonymous={}",
                pageNum, pageSize, ip, port, type, country, status, anonymous);
                
        Map<String, Object> params = new HashMap<>();
        params.put("pageNum", pageNum);
        params.put("pageSize", pageSize);
        params.put("ip", ip);
        params.put("port", port);
        params.put("type", type);
        params.put("country", country);
        params.put("status", status);
        params.put("anonymous", anonymous);
        
        PageResult<ProxyIp> pageResult = proxyIpService.listProxies(params);
        return CommonResult.success(pageResult);
    }

    @PostMapping("/validate/{id}")
    @Operation(summary = "验证代理IP", description = "验证指定ID的代理IP是否有效")
    @PreAuthorize("hasAuthority('crawler:proxy:validate')")
    public CommonResult<Boolean> validateProxy(
            @Parameter(description = "代理IP ID", required = true) @PathVariable Long id) {
        log.info("验证代理IP: {}", id);
        boolean isValid = proxyIpService.validateProxy(id);
        return CommonResult.success(isValid, isValid ? "代理IP有效" : "代理IP无效");
    }

    @PostMapping("/validate")
    @Operation(summary = "批量验证代理IP", description = "批量验证指定ID的代理IP是否有效")
    @PreAuthorize("hasAuthority('crawler:proxy:validate')")
    public CommonResult<Map<Long, Boolean>> validateProxies(
            @Parameter(description = "代理IP ID列表") @RequestBody List<Long> ids) {
        log.info("批量验证代理IP: {}", ids);
        Map<Long, Boolean> results = proxyIpService.validateProxies(ids);
        return CommonResult.success(results, "批量验证代理IP完成");
    }

    @PostMapping("/batch/import")
    @Operation(summary = "批量导入代理IP", description = "批量导入代理IP")
    @PreAuthorize("hasAuthority('crawler:proxy:create')")
    public CommonResult<Integer> batchImportProxies(
            @Parameter(description = "代理IP列表") @RequestBody List<ProxyIp> proxyIps) {
        log.info("批量导入代理IP，数量 {}", proxyIps.size());
        int count = proxyIpService.batchImportProxies(proxyIps);
        return CommonResult.success(count, "批量导入代理IP成功，成功导入" + count + "条");
    }

    @PostMapping("/batch/delete")
    @Operation(summary = "批量删除代理IP", description = "批量删除代理IP")
    @PreAuthorize("hasAuthority('crawler:proxy:delete')")
    public CommonResult<Integer> batchDeleteProxies(
            @Parameter(description = "代理IP ID列表") @RequestBody List<Long> ids) {
        log.info("批量删除代理IP: {}", ids);
        int count = proxyIpService.batchDeleteProxies(ids);
        return CommonResult.success(count, "批量删除代理IP成功，成功删除" + count + "条");
    }

    @GetMapping("/available")
    @Operation(summary = "获取可用代理IP列表", description = "获取可用的代理IP列表")
    @PreAuthorize("hasAuthority('crawler:proxy:view')")
    public CommonResult<List<ProxyIp>> getAvailableProxies(
            @Parameter(description = "类型：HTTP、HTTPS、SOCKS4、SOCKS5") @RequestParam(required = false) String type,
            @Parameter(description = "国家/地区") @RequestParam(required = false) String country,
            @Parameter(description = "是否匿名") @RequestParam(required = false) Boolean anonymous,
            @Parameter(description = "最大延迟(毫秒)") @RequestParam(required = false) Integer maxDelay,
            @Parameter(description = "限制返回的数量") @RequestParam(required = false, defaultValue = "10") Integer limit) {
        
        log.info("获取可用代理IP列表，参数 type={}, country={}, anonymous={}, maxDelay={}, limit={}",
                type, country, anonymous, maxDelay, limit);
                
        Map<String, Object> params = new HashMap<>();
        params.put("type", type);
        params.put("country", country);
        params.put("anonymous", anonymous);
        params.put("maxDelay", maxDelay);
        params.put("limit", limit);
        
        List<ProxyIp> proxyIps = proxyIpService.getAvailableProxies(params);
        return CommonResult.success(proxyIps);
    }

    @PostMapping("/discover")
    @Operation(summary = "自动发现新代理", description = "从代理网站自动发现新的代理IP")
    @PreAuthorize("hasAuthority('crawler:proxy:discover')")
    public CommonResult<Integer> discoverProxies() {
        log.info("自动发现新代理IP");
        int count = proxyIpService.discoverProxies();
        return CommonResult.success(count, "自动发现代理IP完成，发现" + count + "条新代理");
    }

    @PostMapping("/random")
    @Operation(summary = "获取随机代理", description = "获取一个随机的有效代理IP")
    @PreAuthorize("hasAuthority('crawler:proxy:view')")
    public CommonResult<ProxyIp> getRandomProxy(
            @Parameter(description = "类型：HTTP、HTTPS、SOCKS4、SOCKS5") @RequestParam(required = false) String type) {
        log.info("获取随机代理IP，类型 {}", type);
        ProxyIp proxyIp = proxyIpService.getRandomProxy(type);
        return CommonResult.success(proxyIp);
    }
} 
